package handler

import (
	"net/http"

	"markedit/internal/middleware"
	"markedit/internal/model"
	"markedit/internal/service"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type UserHandler struct {
	userService *service.UserService
	logger      *logrus.Logger
}

func NewUserHandler(userService *service.UserService, logger *logrus.Logger) *UserHandler {
	return &UserHandler{
		userService: userService,
		logger:      logger,
	}
}

// Register 用户注册
func (h *UserHandler) Register(c *gin.Context) {
	var req model.UserRegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	// 验证必填字段
	if req.Username == "" || req.Email == "" || req.Password == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "用户名、邮箱和密码不能为空",
		})
		return
	}

	user, err := h.userService.Register(&req)
	if err != nil {
		h.logger.Errorf("用户注册失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户注册成功: %s", user.Username)
	c.JSON(http.StatusCreated, gin.H{
		"message": "注册成功",
		"user": gin.H{
			"id":       user.ID,
			"username": user.Username,
			"email":    user.Email,
		},
	})
}

// Login 用户登录
func (h *UserHandler) Login(c *gin.Context) {
	var req model.UserLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	// 验证必填字段
	if req.Username == "" || req.Password == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "用户名和密码不能为空",
		})
		return
	}

	response, err := h.userService.Login(&req)
	if err != nil {
		h.logger.Errorf("用户登录失败: %v", err)
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户登录成功: %s", req.Username)
	c.JSON(http.StatusOK, response)
}

// GetProfile 获取用户信息
func (h *UserHandler) GetProfile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	user, err := h.userService.GetUserByID(userID)
	if err != nil {
		h.logger.Errorf("获取用户信息失败: %v", err)
		c.JSON(http.StatusNotFound, gin.H{
			"error": "用户不存在",
		})
		return
	}

	profile := &model.UserProfile{
		ID:       user.ID,
		Username: user.Username,
		Email:    user.Email,
		Avatar:   user.Avatar,
	}

	c.JSON(http.StatusOK, profile)
}

// UpdateProfile 更新用户信息
func (h *UserHandler) UpdateProfile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	var req model.UserUpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	user, err := h.userService.UpdateUser(userID, &req)
	if err != nil {
		h.logger.Errorf("更新用户信息失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户信息更新成功: %s", user.Username)
	c.JSON(http.StatusOK, gin.H{
		"message": "更新成功",
		"user": gin.H{
			"id":       user.ID,
			"username": user.Username,
			"email":    user.Email,
			"avatar":   user.Avatar,
		},
	})
}

// ChangePassword 修改密码
func (h *UserHandler) ChangePassword(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	var req model.ChangePasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	// 验证必填字段
	if req.OldPassword == "" || req.NewPassword == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "旧密码和新密码不能为空",
		})
		return
	}

	err := h.userService.ChangePassword(userID, &req)
	if err != nil {
		h.logger.Errorf("修改密码失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户修改密码成功: %s", userID)
	c.JSON(http.StatusOK, gin.H{
		"message": "密码修改成功",
	})
}

// Logout 用户登出
func (h *UserHandler) Logout(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	// 从请求头获取token
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "缺少token",
		})
		return
	}

	token := authHeader[7:] // 去掉 "Bearer " 前缀

	err := h.userService.Logout(token)
	if err != nil {
		h.logger.Errorf("用户登出失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "登出失败",
		})
		return
	}

	h.logger.Infof("用户登出成功: %s", userID)
	c.JSON(http.StatusOK, gin.H{
		"message": "登出成功",
	})
}